import { ref, computed, watch } from 'vue';
import { pinia, defineStore, acceptHMRUpdate } from '@shared/internal/pinia';
import { find } from 'lodash-es';
import { clientWorkflowSettings } from '@shared/internal/client';
import { addObjectToArray, updateObjectInSmallArray } from '@shared/utils/array';
import { getTeamTaskListApi } from '@main/service/team';
import { productHandleApi } from '@main/service/workflow';
import type { ContentProperties } from './types/workflow';
import type { WorkflowSettingsProperties } from '#common/types/settings';
import type { taskProperties } from '@main/socket/type';

export const useWorkflowStore = defineStore('workflow', () => {
  //----------------------工作流----------------------
  const historyContentArray = ref<ContentProperties[]>([]);

  /**
   * 监听任务变化
   */
  watch(
    () => historyContentArray.value,
    (n, o) => {
      console.log('HistoryContent', { ...o }, '====>', { ...n });
    },
    {
      deep: true
    }
  );

  /**
   * 已有任务初始化
   */
  function initHistoryContentArray() {
    historyContentArray.value = [];
    getTeamTaskListApi().then((taskList) => {
      taskList.forEach((task) => {
        addContentAction(task);
      });
    });
  }

  /**
   * 我的工作流当前唯一id
   * 仅通过接收协议请求更改
   */
  const myContentCurrentUniqueId = ref<string>('');

  /**
   * 任务工作流当前唯一id
   * 通过侧边栏点击更改
   */
  const taskContentCurrentUniqueId = ref<string>('');

  /**
   * 获取历史内容
   */
  const getHistoryContentArray = computed(() =>
    historyContentArray.value.filter((x) => !x.hidding)
  );

  /**
   * 获取默认内容
   */
  const getInitContent: ContentProperties = {
    id: '',
    product_title: '',
    begin_title: '',
    video_names: [''],
    is_deepAi_override: false,
    is_sell_point_override: false,
    disabledUseMoFang: true
  };

  /**
   *获取我的内容
   * @param id 唯一id
   * @returns
   */
  const getMyContent = computed(() => getContentByUniqueId(myContentCurrentUniqueId.value));
  /**
   *获取任务内容
   * @param id 唯一id
   * @returns
   */
  const getTaskContent = computed(() => getContentByUniqueId(taskContentCurrentUniqueId.value));

  /**
   *设置我的内容
   * @param id 唯一id
   * @returns
   */
  const setMyContentUniqueId = (id: string) => {
    myContentCurrentUniqueId.value = id;
  };

  /**
   *设置任务内容
   * @param id 唯一id
   * @returns
   */
  const setTaskContentUniqueId = (id: string) => {
    taskContentCurrentUniqueId.value = id;
  };

  /**
   *获取内容数组
   * @param matchCondition 条件
   * @returns
   */
  const getContents = (matchCondition: (item: ContentProperties) => boolean) => {
    return computed(() => getHistoryContentArray.value.filter(matchCondition));
  };

  /**
   *获取内容
   * @param id 唯一id
   * @returns
   */
  const getContentByUniqueId = (id: string) => {
    return computed(() => historyContentArray.value.find((x) => x.id == id));
  };

  /**
   * 获取内容
   * @param product_id 工作流商品id
   * @returns
   */
  const getContentByProductId = (product_id: number) => {
    return computed(() => historyContentArray.value.find((x) => x.product_id == product_id));
  };

  /**
   * 获取内容
   * @param task_id 任务id
   * @returns
   */
  const getContentByTaskId = (task_id: number) => {
    return computed(() => historyContentArray.value.find((x) => x.task && x.task.id == task_id));
  };

  /**
   * 请求内容处理
   * @param content 内容
   */
  function requestContentHandle(content: ContentProperties) {
    productHandleApi({
      product_title: content.product_title
    }).then((productHandleRes) => {
      setContentAction({
        ...content,
        ...productHandleRes,
        begin_title: content.product_title,
        is_deepAi_override: !productHandleRes.open_deepAi,
        stepwise: [...content.stepwise!, 1]
      });
      setTimeout(() => {
        const content = getContentByProductId(productHandleRes.product_id);
        if (content.value && !content.value.product_name) {
          setContentAction({
            ...content.value,
            error_message: '普通商品信息获取超时'
          });
        }
      }, 15 * 1000);

      if (productHandleRes.open_deepAi)
        setTimeout(() => {
          const content = getContentByProductId(productHandleRes.product_id);
          if (content.value && !content.value.sell_copy) {
            setContentAction({
              ...content.value,
              deepAi_error_message: '深度商品信息获取超时'
            });
          }
        }, 45 * 1000);
    });
  }

  /**
   * 新增内容
   * @param content 商品标题|任务
   * @returns
   */
  function addContentAction(content: string | taskProperties) {
    const isProtocolMode = typeof content === 'string';
    let shouldExecuteHandle = content !== '';
    let newContent: ContentProperties = {
      ...getInitContent,
      stepwise: [0]
    };

    if (isProtocolMode) {
      //通过协议或其他方式
      console.log(content);
      const historyContent = find(
        historyContentArray.value,
        (historyContent) =>
          historyContent.begin_title == '' || historyContent.begin_title == content
      );
      console.log(historyContent);
      setTaskContentUniqueId('');
      if (historyContent) {
        if(historyContent.begin_title != '') {
          setContentAction({
            ...historyContent,
            product_title: historyContent.begin_title
          });
        }
        newContent = historyContent;
        shouldExecuteHandle = !Boolean(newContent.product_id);
        setMyContentUniqueId(newContent.id);
      } else {
        newContent.product_title = content;
        const newArray = addObjectToArray(historyContentArray.value, newContent);
        historyContentArray.value = newArray;
        newContent = newArray[newArray.length - 1];
        setMyContentUniqueId(newContent.id);
      }
    } else {
      //任务通知
      newContent.task = content;
      newContent.product_title = content.product_title;
      historyContentArray.value = addObjectToArray(historyContentArray.value, newContent);
    }
    console.log(shouldExecuteHandle);
    if (shouldExecuteHandle) requestContentHandle(newContent);
  }

  /**
   * 修改内容
   * @param content 内容
   * @param keyName 匹配键 default id
   */
  function setContentAction(content: ContentProperties, keyName: keyof ContentProperties = 'id') {
    historyContentArray.value = updateObjectInSmallArray(
      historyContentArray.value,
      content,
      keyName
    );
  }

  /**
   * 删除任务内容
   * @param content 内容
   */
  function deleteContentByTaskIdsAction(task_ids: number[]) {
    const removeIdList = historyContentArray.value
      .filter((x) => x.task && task_ids.includes(x.task.id) && !x.product_id)
      .map((x) => x.id);
    historyContentArray.value = historyContentArray.value.filter(
      (x) => !removeIdList.includes(x.id)
    );
  }

  //----------------------草稿目录----------------------
  const settings = ref<WorkflowSettingsProperties>({} as any);

  /**
   * 获取剪映草稿目录
   */
  const getDraftDirectory = computed(() => {
    return settings.value?.draftDirectory ?? '';
  });

  /**
   * 获取视频素材目录
   */
  const getMaterialDirectory = computed(() => {
    return settings.value?.materialDirectory ?? '';
  });

  /**
   * 设置目录文件夹
   * @param newSettings 路径
   * @param conf 是否本地化存储
   */
  function setDirectorySetting(newSettings: Partial<WorkflowSettingsProperties>, conf = false) {
    settings.value = { ...settings.value, ...newSettings };
    if (!conf) clientWorkflowSettings.set('directory', { ...settings.value });
  }

  return {
    historyContentArray,
    myContentCurrentUniqueId,
    taskContentCurrentUniqueId,
    getHistoryContentArray,
    getInitContent,
    getMyContent,
    getTaskContent,
    setMyContentUniqueId,
    setTaskContentUniqueId,
    getContents,
    getContentByUniqueId,
    getContentByProductId,
    getContentByTaskId,
    initHistoryContentArray,
    addContentAction,
    requestContentHandle,
    setContentAction,
    deleteContentByTaskIdsAction,
    settings,
    getDraftDirectory,
    getMaterialDirectory,
    setDirectorySetting
  };
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useWorkflowStore, import.meta.hot));
}

export function useWorkflowStoreWithOut() {
  return useWorkflowStore(pinia);
}
